<!-- <title>瑞众银保“五个一”功成--客户经理维护记录<title> -->
<style lang="less" scoped>
@import '@css/list.less';
</style>

<template>
  <div id="app">
    <van-sticky>
      <div class="title">维护记录</div>
    </van-sticky>
    <div
      style="margin: 20px auto; text-align: center"
      v-if="recentYb51WeeklyPreserveRecordList.length == 0"
    >
      暂无数据
    </div>
    <van-collapse
      v-model="activeNames"
      @change="onchangecollapse"
      accordion
      v-for="(item, index) of recentYb51WeeklyPreserveRecordList"
      :key="index"
    >
      <van-collapse-item :title="`对象：${item.target}`" :label="item.createDate" :name="index">
        <van-form @submit="onupdateYb51WeeklyPreserveRecord(index)" @failed="onFailed">
          <van-cell-group inset>
            <van-field
              :readonly="ShowUpdate != index"
              :class="{ backgroundRed: ShowUpdate == index }"
              class="fbox"
              v-model="item.way"
              :name="`way${index}`"
              label="渠道/网点"
              placeholder="请填写渠道/网点"
              :rules="[{ required: true, message: '不能为空' }]"
            ></van-field>

            <van-field
              :readonly="ShowUpdate != index"
              :class="{ backgroundRed: ShowUpdate == index }"
              class="fbox"
              v-model="item.target"
              :name="`target${index}`"
              label="维护对象"
              placeholder="请填写维护对象"
              :rules="[{ required: true, message: '不能为空' }]"
            ></van-field>

            <van-field
              :is-link="ShowUpdate == index"
              class="fbox"
              v-model="item.preserveDate"
              :name="`preserveDate${index}`"
              label="维护时间"
              placeholder="请填写维护时间"
              :rules="[{ required: true, message: '不能为空' }]"
              readonly
              @click="ShowUpdate != index ? '' : onshowPickerDate(index)"
            ></van-field>
            <van-field
              :readonly="ShowUpdate != index"
              :class="{ backgroundRed: ShowUpdate == index }"
              autosize
              type="textarea"
              class="fbox"
              v-model="item.preserveForm"
              :name="`preserveForm${index}`"
              label="维护形式"
              placeholder="陪同参与、邀约出行、组织团康"
              :rules="[{ required: true, message: '不能为空' }]"
            ></van-field>

            <van-field
              :readonly="ShowUpdate != index"
              :class="{ backgroundRed: ShowUpdate == index }"
              autosize
              type="textarea"
              class="fbox"
              v-model="item.evaluation"
              :name="`evaluation${index}`"
              label="维护评估"
              placeholder="互动性、信任度、依赖度"
              :rules="[{ required: true, message: '不能为空' }]"
            ></van-field>
            <van-field :name="`uploader${index}`" label="图片">
              <template #input>
                <van-uploader
                  :deletable="false"
                  v-model="item.uploaderImgList"
                  :max-count="1"
                  :before-read="onbeforeRead"
                  :after-read="onafterRead"
                ></van-uploader>
              </template>
            </van-field>
          </van-cell-group>
          <div class="button" v-if="ShowUpdate != index">
            <van-button block type="primary" @click="onShowupdateYb51WeeklyPreserveRecord(index)"
              >更新</van-button
            >
          </div>
          <div class="button" v-if="ShowUpdate == index">
            <van-button
              block
              type="warning"
              style="width: 35%"
              @click="onCancelupdateYb51WeeklyPreserveRecord()"
              >取消更新</van-button
            >
            <van-button block type="primary" native-type="submit" style="width: 55%"
              >提交</van-button
            >
          </div>
        </van-form>
      </van-collapse-item>
    </van-collapse>

    <van-popup v-model:show="showPickerDate" position="bottom">
      <van-date-picker
        v-model="currentDate"
        @confirm="onConfirmDate"
        @cancel="showPickerDate = false"
        :columns-type="['year', 'month', 'day']"
        title="请选择月日"
        :formatter="formatter"
      ></van-date-picker>
    </van-popup>
  </div>
</template>
<script setup>
import {
  onBeforeMount,
  onMounted,
  onUnmounted,
  watch,
  computed,
  provide,
  inject,
  ref,
  reactive,
  nextTick,
  h
} from 'vue'
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()
const dayjs = inject('$dayjs')
const showPageLoading = inject('showPageLoading')
const hidePageLoading = inject('hidePageLoading')
const showAllNonBaseMenuItem = inject('showAllNonBaseMenuItem')
const hideAllNonBaseMenuItem = inject('hideAllNonBaseMenuItem')
import { isIOS, parseTime, handleFontSize } from '@/utils'
import {
  yb51_weekly_preserve_record_recentYb51WeeklyPreserveRecordList,
  yb51_weekly_preserve_record_updateYb51WeeklyPreserveRecord
} from '@/request/api.js'

onMounted(() => {
  agentcode = route.query.agentcode

  getrecentYb51WeeklyPreserveRecordList()
})

let agentcode


const currentDate = ref([dayjs().format('YYYY'), dayjs().format('MM'), dayjs().format('DD')])
const formatter = (type, option) => {
  if (type === 'year') {
    option.text += '年'
  }
  if (type === 'month') {
    option.text += '月'
  }
  if (type === 'day') {
    option.text += '日'
  }
  return option
}
const showPickerDate = ref(false)
let PickerIndex = 'no'
function onshowPickerDate(index) {
  showPickerDate.value = true
  PickerIndex = index
}
const onConfirmDate = ({ selectedValues }) => {
  recentYb51WeeklyPreserveRecordList.value[PickerIndex].preserveDate = selectedValues.join('-')
  PickerIndex = 'no'
  showPickerDate.value = false
}

const activeNames = ref(['1'])

import { compressImageToTargetSize } from '@/utils'
const targetSize = 1024 * 1024 * 1 // 1M大小
function onbeforeRead(file) {
  return new Promise((resolve, reject) => {
    console.log('压缩前文件大小:', file.size/(1024 * 1024), 'M')
    if (file.size < targetSize) {
      console.log('小于，不用压缩')
      resolve(file)
    } else {
      compressImageToTargetSize(file, targetSize).then((res) => {
        console.log('压缩后的文件大小:',res.size/(1024 * 1024), 'M')
        resolve(res)
      })
    }
  })
}
//文件读取后的回调函数
function onafterRead(file) {
  console.log('读取完毕')
}

function onchangecollapse() {
  onCancelupdateYb51WeeklyPreserveRecord()
}

//更新
const ShowUpdate = ref('no')
function onShowupdateYb51WeeklyPreserveRecord(index) {
  console.log(ShowUpdate.value)
  ShowUpdate.value = index
  console.log(ShowUpdate.value)
}
//取消更新
function onCancelupdateYb51WeeklyPreserveRecord() {
  recentYb51WeeklyPreserveRecordList.value = recentYb51WeeklyPreserveRecordListBackup
    .slice()
    .map((item) => (typeof item === 'object' ? { ...item } : item))
  ShowUpdate.value = 'no'
}
//更新客户经理维护记录
function onupdateYb51WeeklyPreserveRecord(index) {
  showPageLoading()
  // const url = '/updateYb51WeeklyPreserveRecord'
  const recentYb51WeeklyPreserveRecordListparams = recentYb51WeeklyPreserveRecordList.value[index]
  // 删除键 fileUrl,不给更新图片
  delete recentYb51WeeklyPreserveRecordListparams.fileUrl
  const params = JSON.stringify(recentYb51WeeklyPreserveRecordListparams)
  yb51_weekly_preserve_record_updateYb51WeeklyPreserveRecord(params).then((r) => {
    hidePageLoading()
    if (r.status == 200) {
      showNotify({ type: 'success', message: '更新成功' })
    } else {
      showNotify({ type: 'danger', message: '更新失败' })
    }
    getrecentYb51WeeklyPreserveRecordList()
  })
  // var myHeaders = new Headers()
  // myHeaders.append('Content-Type', 'application/json')
  // var requestOptions = {
  //   method: 'POST',
  //   headers: myHeaders,
  //   body: params,
  //   redirect: 'follow'
  // }
  // fetch(`${baseURL + url}`, requestOptions)
  //   .then((response) => response.json())
  //   .then((r) => {
  //     if (r.status == 200) {
  //       showNotify({ type: 'success', message: '更新成功' })
  //     } else {
  //       showNotify({ type: 'danger', message: '更新失败' })
  //     }
  //     getrecentYb51WeeklyPreserveRecordList()
  //   })
  //   .catch((error) => console.log('error', error))
}

function onFailed() {
  console.log('出错了')
}

//获取经理最近三天拜访记录列表
const recentYb51WeeklyPreserveRecordList = ref([])
let recentYb51WeeklyPreserveRecordListBackup = []

function getrecentYb51WeeklyPreserveRecordList() {
  showPageLoading()
  let params = new FormData()
  params.append('agentCode', agentcode)

  yb51_weekly_preserve_record_recentYb51WeeklyPreserveRecordList(params).then((r) => {
    hidePageLoading()
    if (r.status == 200) {
      // agentcode:"zhujiahao"
      // createDate:"2023-06-27 09:48:18"
      // evaluation:"测试测试测试1"
      // fileUrl:"D:/UploadFile/yb51/20230627\\zhujiahao/银保承保清单.txt"
      // id:"1qfa5l16dc7b"
      // modifyDate:"2023-06-27 09:48:18"
      // target:"测试测试测试1"
      // tutorDate:"2023-06-19"
      // way:"测试测试测试1"
      recentYb51WeeklyPreserveRecordList.value = r.data.map((item) => {
        item['uploaderImgList'] = [{ url: item.fileUrl }]
        return item
      })
      recentYb51WeeklyPreserveRecordListBackup = recentYb51WeeklyPreserveRecordList.value
     
      ShowUpdate.value = 'no'
    } else {
      console.log('出错了，请重试')
      alert('出错了，请重试')
    }
  })
}
</script>
